#!/usr/bin/php -n
<?php
//获得工作目录
//遍历当前目录下的md文件:默认
//遍历指定目录下的md文件:-d dirpath
//或者递归遍历当前目录/指定目录下的md文件: -r
//或者只解析当前md文件：  -f mdpath
//输出解析详情：-v
echo "\n";
echo '***********************';
echo "\n";
$options = getopt( 'f:d:r::v::h::e::' );
if ( isset($options['h']) ) {
	echo "-f	转换指定的文件\n";
	echo "-d	转换指定目录下的所有文件\n";
	echo "-r	递归的方式转换,此方式下f参数无效，如果没有制定目录，将递归解析当前目录\n";
	echo "-v	显示解析过程\n";
	echo "无参数  解析当前目录下的所有文件\n";
	exit;
}
$success = array();
$error   = array();

if(isset($options['e'])){
	$from = $options['e'];
}else{
	$from = 'gb2312';
}

if ( isset($options['d']) ) {
	$path = $options['d'];
} else {
	$path = getcwd();
}
if ( isset($options['f']) ) {
	gbToUtf8( $options['f'],$from );
} elseif ( isset($options['r']) ) {
	$iterator = new RecursiveDirectoryIterator($path, FilesystemIterator::KEY_AS_PATHNAME|FilesystemIterator::SKIP_DOTS|FilesystemIterator::CURRENT_AS_SELF|FilesystemIterator::UNIX_PATHS);
	$ii       = new RecursiveIteratorIterator($iterator, RecursiveIteratorIterator::LEAVES_ONLY);
} else {
	$ii = new FilesystemIterator($path, FilesystemIterator::KEY_AS_PATHNAME|FilesystemIterator::UNIX_PATHS|FilesystemIterator::SKIP_DOTS);
}
if ( isset($ii) ) {
	foreach ( $ii as $key=> $v ) {
		if ( is_dir( $key ) ) {
			continue;
		}
		gbToUtf8( $key ,$from);
	}
	if ( isset($options['v']) ) {
		foreach ( $success as $s ) {
			echo $s."\n";
		}
		foreach ( $error as $e ) {
			echo $e."\n";
		}
	}
}

echo "成功转换".count( $success )."个文件\n";
echo "转换失败数量：".count( $error )."\n";
echo '***********************';
echo "\n";
function gbToUtf8( $file ,$from) {
	global $success;
	global $error;
	static $i = 1;
	static $e = 1;
	if ( is_readable( $file ) && is_file( $file ) ) {
		$content = file_get_contents( $file );
		if ( is_writable( dirname( $file ) ) ) {
			if ( mb_check_encoding( $content, $from ) ) {
				$content=mb_convert_encoding( $content, 'utf-8', $from );
				file_put_contents( $file, $content  );
				$success[] = "成功转换文件 {$i} :".$file;
				$i++;
			}
		} else {
			$error[] = "文件写入失败 {$e}:".$file;
			$e++;
		}
	} else {
		$error[] = '文件读取失败:'.$file;
	}
}